package cn.tedu.charging.order.config;



import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;


@Configuration
public class RabbitMQConfig {
    //声明queue,交换机,routingKey, 死信queue,交换机,routingKey
    private static final String ORDER_QUEUE = "order_queue";
    public static final String ORDER_EXCHANGE = "order_exchange";
    public static final String ORDER_ROUTING_KEY = "order_routing_key";
    public static final String ORDER_DEAD_LATTER_QUEUE = "order_dead_latter_queue";
    private static final String ORDER_DEAD_LATTER_EXCHANGE = "order_dead_latter_exchange";
    private static final String ORDER_DEAD_LATTER_ROUTING_KEY = "order_dead_latter_routing_key";


    /**
     * 定义订单队列
     */
    @Bean
    public Queue orderQueue() {
        Map<String, Object> args = new HashMap<String, Object>();
        args.put("x-dead-letter-exchange", ORDER_DEAD_LATTER_EXCHANGE);
        args.put("x-dead-letter-routing-key", ORDER_DEAD_LATTER_ROUTING_KEY);
        //模拟充电充满需要 2分钟  2*60*1000
        Integer ttl =  2 * 60 * 1000;
        //指定消息的存活时间
        args.put("x-message-ttl", ttl);
        //惰性队列,在消息很多的时候,存储到磁盘,避免消息积压,占用内存
        args.put("x-queue-mode", "lazy");
        //消息持久化 不能丢失
        Boolean durable  = true;
        return new Queue(ORDER_QUEUE,durable,true,false,args);
    }

    /**
     * 定义订单交换机
     */
    @Bean
    public DirectExchange orderExchange(){
        return new DirectExchange(ORDER_EXCHANGE);
    }

    /**
     * 把订单队列绑定到订单交换机
     */
    @Bean
    public Binding orderBinding(){
        return BindingBuilder.bind(orderQueue()).to(orderExchange()).with(ORDER_ROUTING_KEY);
    }

    /**
     * 定义死信的队列
     */
    @Bean
    public Queue deadLetterQueue(){
        return new Queue(ORDER_DEAD_LATTER_QUEUE,true,false,false);
    }

    /**
     * 定义死信的交换机
     */
    @Bean
    public DirectExchange deadLetterExchange(){
        return new DirectExchange(ORDER_DEAD_LATTER_EXCHANGE,true,false);
    }

    /**
     * 将死信队列和死信交换机进行绑定
     */
    @Bean
    public Binding deadLetterBindingDeadLetter(){
        return BindingBuilder.bind(deadLetterQueue()).to(deadLetterExchange())
                .with(ORDER_DEAD_LATTER_ROUTING_KEY);
    }
}
